package com.edu.controller;


import com.edu.bean.Book;
import com.edu.bean.User;
import com.edu.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;



    @RequestMapping("/showBook")
    public ModelAndView showBook(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "5") int size,@RequestParam(defaultValue = "-1") String keyword){
        ModelAndView mv = new ModelAndView();
        System.out.println(keyword);


        if(keyword.equals("-1")){
            PageHelper.startPage(page,size);
            List<Book> books = bookService.findAllBook();
            System.out.println(books);
            PageInfo<Book> pageInfo = new PageInfo<Book>(books);

            mv.addObject("pageInfo",pageInfo);
            mv.setViewName("/book.jsp");
            return mv;
        }else{
            PageHelper.startPage(page,size);
            List<Book> books = bookService.searchBook(keyword);
            PageInfo<Book> pageInfo = new PageInfo<Book>(books);

            mv.addObject("pageInfo",pageInfo);
            mv.setViewName("/book.jsp");
            System.out.println("------------------------------");
            return mv;
        }

    }
    @RequestMapping("/deleteBook")
    public ModelAndView deleteBook(int bookId, @SessionAttribute("loginUser") User user){

        System.out.println(user);
        if (user==null){
            return new ModelAndView("redirect:/login");
        }
        bookService.deleteBook(bookId);
        System.out.println(bookId);
        ModelAndView mv = new ModelAndView();

        mv.setViewName("showBook");
        return mv;
    }
    @PostMapping("/updateBook")

    public ResponseEntity<?> updateBook(@RequestBody Book book){
        System.out.println(book);
        System.out.println("成功"+book.getChangeDate());
        int i = bookService.updateBook(book);
        return ResponseEntity.ok("修改成功 " + book.getBookId());
    }

    @GetMapping("/{bookId}")

    public ModelAndView selectOneBook(@PathVariable("bookId") int bookId){
        ModelAndView mv = new ModelAndView();
        Book book = bookService.selectOneBook(bookId);
        System.out.println(book);
        mv.addObject("book",book);
        mv.setViewName("/oneBook.jsp");
        return mv;
    }

    @RequestMapping("/searchBook")
    public ModelAndView deleteBook(String keyword){



        ModelAndView mv = new ModelAndView();


        return mv;
    }
}
